#include <stm32f1xx_hal.h>
#include <ws2812.hpp>
#include <cmath>

extern "C" {
extern SPI_HandleTypeDef hspi2;
}

WS2812 strip(&hspi2);

void WS2812::init() {
    uint8_t zero = 0;
    HAL_SPI_Transmit(spi, &zero, 1, HAL_MAX_DELAY);
    HAL_Delay(100);
}

void WS2812::render() {
    for (int i = 0; i < WS_NLEDS; i++)
        tx_buffer[i] = color_buffer[i];
    HAL_SPI_Transmit_DMA(spi, (uint8_t *) &tx_buffer, sizeof(tx_buffer));
}

void WS2812::drawPixel(float pos, float size, CRGB color) {
    if (size < 1)
        return;
    float start = pos - size / 2;
    int istart, iend;

    if (start > 0) {
        istart = ceilf(start);
        color_buffer[istart - 1] += color * (istart - start);
    } else {
        istart = 0;
    }

    float end = start + size;
    if (end < WS_NLEDS - 1) {
        iend = floorf(end);
        color_buffer[iend + 1] += color * (end - iend);
    } else {
        iend = WS_NLEDS - 1;
    }

    for (int i = istart; i <= iend; i++)
        color_buffer[i] += color;
}